<?php
session_start();
require_once( 'stock_db.php' );
require_once('employee_db.php');

$m_emp = new M_Employee();
$type = new M_Stock();
$user_id = $_SESSION['userid'];

$inital_status = 2;
$inital_status_purchase=2;
$mode_type = getPost('m') ;

if (isset($mode_type) && $mode_type != "") {

    if ($mode_type == 'load_req') {
        $dt = '';
        $df = '';

        if (getPost('datefrom') != '') 
            $df = convertDate(getPost('datefrom'));

		if (getPost('dateto')  != '') 
            $dt = convertDate(getPost('dateto'));

        $status = getPost('status')  ;
        $no = getPost('no')  ;
        $name = getPost('name')  ;

        $result = $type->loadRequest($no, $status, $df, $dt, $name,0,$user_id);
        $rows = $type->getRowCount();
        $i = 1;
        $html = "";
        if ($rows > 0) {
            $data = array();
            while ($row = $result->FetchRow()) {
                $data[] = array(0, $row['id'], $row['requestdate'], $row['req_no'],$row['request_by'], $row['amt'], $row['statusname'], $row['status']);
            }
        } else {
            $data = array();
        }

        $arr = array('aaData' => $data);

        echo json_encode($arr);
		
    } else if ($mode_type=='upStatus'){
		$id= getPost('id');
		$status= getPost('status');
		$type->update_status_request($id, $status,$user_id);
		
		echo 0;
	} else if ($mode_type=='upStatusPO'){
		$id= getPost('id');
		$status= getPost('status');
		$type->update_status_purchage($id, $status,$user_id);
		
		echo 0;
    } else if ($mode_type=='load_po'){
        $dt = '';
        $df = '';

        if (getPost('datefrom') != '') {
            $df = convertDate(getPost('datefrom'));//$y . '/' . $m . '/' . $d;
        }

        if (getPost('dateto')  != '') {
            $dt = convertDate(getPost('dateto'));//$y . '/' . $m . '/' . $d;
        }
		$admin_flag=getPost('app_flage');
        $status = getPost('status')  ;
        $no = getPost('no')  ;
        $name = getPost('name')  ;
        $rq = getPost('rq');
		$supplier= getPost('supplier');
        $result = $type->loadPurchase($rq,$no, $status, $df, $dt, $name,0,$user_id, $supplier,$admin_flag);
        $rows = $type->getRowCount();
        $i = 1;
        $html = "";
        if ($rows > 0) {
            $data = array();
            while ($row = $result->FetchRow()) {
                $data[] = array(0, $row['id']
				, $row['purchasedate']
				, $row['po_no']
				, $row['supplier_name']
				, $row['request_by']
				, $row['amt']
				, number_format($row['total'],2,'.',',') 
				, number_format($row['discount'],2,'.',',') 
				, number_format($row['total']-$row['discount'],2,'.',',') 
				, $row['statusname']
				, $row['status']);
            }
        } else {
            $data = array();
        }

        $arr = array('aaData' => $data);

        echo json_encode($arr); 
        
    }else if ($mode_type=='load_shipment'){
         $dt = '';
        $df = '';

        if (getPost('datefrom') != '') {
         
            $df = convertDate(getPost('datefrom'));//$y . '/' . $m . '/' . $d;
        }

        if (getPost('dateto')  != '') {
            
            $dt =convertDate(getPost('dateto')); //$y . '/' . $m . '/' . $d;
        }
        $code = getPost('code')  ;
        $pname = getPost('pname')  ;
        $ename = getPost('ename');
        
        $result = $type->loadShipment( $code, $pname, $df, $dt, $ename);
        $rows = $type->getRowCount();
        $i = 1;
        $html = "";
        if ($rows > 0) {
            $data = array();
            while ($row = $result->FetchRow()) {
                $data[] = array(0, $row['id'], $row['shipmentdate'], $row['name'], $row['remark'] , $row['amt'] );
            }
        } else {
            $data = array();
        }

        $arr = array('aaData' => $data);

        echo json_encode($arr); 
        
    }else if ($mode_type=='load_ro'){
        $dt = '';
        $df = '';

        if (getPost('datefrom') != '') {
           // list($d, $m, $y) = split('/', getPost('datefrom') );
            $df = convertDate(getPost('datefrom'));//$y . '/' . $m . '/' . $d;
        }

        if (getPost('dateto')  != '') {
            //list($d, $m, $y) = split('/', getPost('dateto'));
            $dt =convertDate(getPost('dateto')); //$y . '/' . $m . '/' . $d;
        }

        $status = getPost('status')  ;
        $no = getPost('no')  ;
        $name = getPost('name')  ;
        $ro = getPost('ro');
        
        $result = $type->loadreceive($no,$ro, $status, $df, $dt, $name);
        $rows = $type->getRowCount();
        $i = 1;
        $html = "";
        if ($rows > 0) {
            $data = array();
            while ($row = $result->FetchRow()) {
                $data[] = array(0, $row['id'], $row['purchasedate'], $row['po_no'] , $row['orderby'], $row['receivedate'], $row['ro_no']
                            ,$row['receiveby'], $row['amt'],number_format($row['total'],2,'.',','),$row['statusname'] , $row['status']);
            }
        } else {
            $data = array();
        }

        $arr = array('aaData' => $data);

        echo json_encode($arr); 
	}else if ($mode_type=='load_Pay'){
        $dt = '';
        $df = '';

        if (getPost('datefrom') != '') {
           // list($d, $m, $y) = split('/', getPost('datefrom') );
            $df = convertDate(getPost('datefrom'));//$y . '/' . $m . '/' . $d;
        }

        if (getPost('dateto')  != '') {
            //list($d, $m, $y) = split('/', getPost('dateto'));
            $dt =convertDate(getPost('dateto')); //$y . '/' . $m . '/' . $d;
        }

        $status = getPost('status')  ;
        $no = getPost('no')  ;
        $name = getPost('name')  ;
        $ro = getPost('ro');
        
        $result = $type->load_pay_stock($no,$ro, $status, $df, $dt, $name);
        $rows = $type->getRowCount();
        $i = 1;
        $html = "";
        if ($rows > 0) {
            $data = array();
            while ($row = $result->FetchRow()) {
                $data[] = array(0, $row['id'], 
				$row['purchasedate'], 
				$row['po_no'] , 
				$row['orderby'], 
				$row['receivedate'], 
				$row['ro_no']
				,$row['receiveby'], 
				number_format($row['amt'],2,'.',','),
				$row['total'],
				$row['pay_by'] , 
				$row['paydate']);
            }
        } else {
            $data = array();
        }

        $arr = array('aaData' => $data);

        echo json_encode($arr); 
    }else if ($mode_type=='load_stock'){
    
        $n = getPost('name');
        $t = getPost('type');
        $compare = getPost('compare');
        $val = getPost('value');
        
        $result = $type->loadStock($n ,$t, $compare,  $val);
        $rows = $type->getRowCount();
        $i = 1;
        $html = "";
        if ($rows > 0) {
            $data = array();
            while ($row = $result->FetchRow()) {
                $data[] = array(0, $row['id'], $row['pid'], $row['code'], $row['name'], $row['typename'] , $row['amt'], number_format(  $row['cost'],2,'.',''), number_format(  $row['cost'] * $row['amt'],2,'.',','));
            }
        } else {
            $data = array();
        }

        $arr = array('aaData' => $data);

        echo json_encode($arr); 
		
    }else if ($_POST['m'] == 'pd_code'){
		$return  = array();
		$code=$_POST['code'];
		$amt = $_POST['amt'];
		$result = $type->findProductByCode($code);
		
		if ($type->getRowCount() > 0 ){
			$row=$result->FetchRow();
			if (($row['amt'] - $amt) < 0){
				$return=array('result'=>2 ,'txt'=>'สินค้าไม่พอจำหน่าย');
				 
			} else{	
				$return=array('result'=>1 ,'val'=>$row);	
			}
		
		}else {
			$return=array('result'=>0 ,'txt'=>'ไม่พบข้อมูล');
		}
		echo json_encode($return);
		
	   
    }else if ($mode_type == 'getRuning') {
        $t = $_POST['t'];
        $no = $type->getRunning($t);
        echo $no;
    } else if ($mode_type == 'prd_detail') {
        $id = getPost('id');
        $m_type = getPost('type');
        
        if ($m_type==='RO'){
            $result = $type->loadProductDetail_Purchase($id);
            $rows = $type->getRowCount();
            $i = 1;
            $html = "";
            if ($rows > 0) {
                $data = array();
                while ($row = $result->FetchRow()) {
                $data[] = array(0, $row['id'], $row['code'], $row['productname'], $row['amt'],$row['amt_ro'],$row['cost'],$row['discount'] ,($row['amt'] * $row['cost']) - $row['discount'] );
                }
            } else {
                $data = array();
            }
        }else if ($m_type==='PO'){
            $result = $type->loadProductDetail_Purchase($id);
            $rows = $type->getRowCount();
            $i = 1;
            $html = "";
            if ($rows > 0) {
                $data = array();
                while ($row = $result->FetchRow()) {
                $data[] = array(0, $row['id'], $row['code'],$row['typename'], $row['productname'], $row['amt'],$row['cost'],$row['discount'] ,($row['amt'] * $row['cost']) - $row['discount'] );
                }
            } else {
                $data = array();
            }
        }else if ($m_type=='SM'){
			$result = $type->loadProductDetail_shipment($id);
            $rows = $type->getRowCount();
            $i = 1;
            $html = "";
            if ($rows > 0) {
                $data = array();
                while ($row = $result->FetchRow()) {
					 $data[] = array(0, $row['id'] ,$row['code'] , $row['name'], $row['amt']);
                }
            } else {
                $data = array();
            }
			 
		}
        else{
            $result = $type->loadProductDetail($id);
       
            $rows = $type->getRowCount();
            $i = 1;
            $html = "";
            if ($rows > 0) {
                $data = array();
                while ($row = $result->FetchRow()) {
                    $data[] = array(0, $row['id'] ,$row['typename'] , $row['productname'], $row['amt']);
                }
            } else {
                $data = array();
            }
            
        }
        $arr = array('aaData' => $data);

        echo json_encode($arr);
    } else if ($mode_type == 'getDetail') {
        $id = $_POST['id'];
        $result = $type->loadRequest('', 0, '', '', '', $id);
        $row = $result->FetchRow();
        echo json_encode($row);
        
    }else if ($mode_type=='getReceiveDetail'){
        $id = $_POST['id'];

        $result = $type->loadreceive('','', 0, '', '', '', $id);
        $row = $result->FetchRow();
		
		if ($row['ro_no']==''){
			$re = $type->getRunning("RE");
			$type->updateReceiveNo($id,$re);
			$row['ro_no']=$re;
		}
		
        echo json_encode($row);
		
     }else if ($mode_type=='getPaymentDetail'){
        $id = $_POST['id'];

        $result = $type->loadreceive('','', 0, '', '', '', $id);
        $row = $result->FetchRow();
		
		if ($row['pa_no']==''){
			$re = $type->getRunning("PA");
			$type->updatePayNo($id,$re);
			$row['pa_no']=$re;
		}
		
        echo json_encode($row);    
    }else if ($mode_type=='getPurchaseDetail'){
        $id = $_POST['id'];
        $result = $type->loadPurchase('','', 0, '', '', '', $id);
        $row = $result->FetchRow();
        echo json_encode($row);
    }else if ($mode_type=='getShipmentDetail'){
	
		$id = $_POST['id'];
        $result = $type->loadShipment('','', '', '', '',   $id);
        $row = $result->FetchRow();
        echo json_encode($row);
		
    } else if ($mode_type == 'getProductwithDetail') {
        $t_product = getPost('t') ;//$_POST['t'];

        $result = $type->loadProduct($t_product);
        $rows = $type->getRowCount();
        $i = 1;
        $html = "";
        if ($rows > 0) {
            $data = array();
            $id = array();

            while ($row = $result->FetchRow()) {
               /* $id['id'] = $row['id'];
                $id['label'] = $row['name'];
                $id['cost']=$row['cost'];
				$id['code']=$row['code'];
				$data[] = $id;
				*/
				
                $data[$row['id']] = $row;
            }
        } else {
            $data = array();
        }

        echo json_encode($data);
        
    } else if ($mode_type == 'getProduct') {
		 $t_product = getPost('t') ;//$_POST['t'];
        $result = $type->loadProduct( $t_product);
        $rows = $type->getRowCount();
        $i = 1;
        $html = "";
        if ($rows > 0) {
            $data = array();
            $id = array();

            while ($row = $result->FetchRow()) {
                $id['id'] = $row['id'];
                $id['label'] = $row['name'];
				 $id['code'] = $row['code'];
                $data[] = $id;
            }
        } else {
            $data = array();
        }

        echo json_encode($data);
    }else if ($mode_type == 'getProductShipment') {
        $result = $type->loadProduct_for_shipment();
        $rows = $type->getRowCount();
        $i = 1;
        $html = "";
        if ($rows > 0) {
            $data = array();
            $id = array();

            while ($row = $result->FetchRow()) {
                /*$id['id'] = $row['id'];
                $id['label'] = $row['name'];
				 $id['code'] = $row['code'];
                $data[] = $id;*/
				$data[$row['id']] = $row;
            }
        } else {
            $data = array();
        }

        echo json_encode($data);   
    }else if ($mode_type=='getCustomer'){
       

        $result = $type->loadCustomer();
        $rows = $type->getRowCount();
        $i = 1;
        $html = "";
        if ($rows > 0) {
            $data = array();
            $id = array();

            while ($row = $result->FetchRow()) {
                $id['id'] = $row['id'];
                $id['label'] = $row['name'];
                $data[] = $id;
            }
        } else {
            $data = array();
        }

        echo json_encode($data);
        
    }else if ($mode_type=='up_stock'){
        $id = getPost('id');
        $pid= getPost('pid');
        $amt = getPost('amt');
        
         $strcipt = $type->update_stock($id,$pid,$amt);
         
    }else if($mode_type=='update_receive'){
        $ar=array();
        //$ar['id']=  getPost('mid');
        //$ar['ro_no']=  getPost('re');
        $ar['total'] = getPost('total');
		$ar['receive_by']=$user_id;
        $ar['receive_date'] = date("Y/m/d H:i:s");
        $ar['updateby']=$user_id;
        $ar['updatedate']=date("Y/m/d H:i:s");
        $ar['status_ro']=5; // complete recieve product
        
        $strcipt = $type->updateReciveData(getPost('mid'),$ar);
        
        $var = getPostArray('list');
         foreach ($var as $value) {
            //$value['po_id'] = $id;
            $type->UpdateReceiveDataDetail($value);
        }
        $status = $type->getRoStatusById(5);
        $result=$type->loadreceive('','',   0,  '',  '',  '',getPost('mid'));

        $row = $result->FetchRow();
         echo json_encode(array(0, $row['id'], $row['purchasedate'], $row['po_no'] , $row['orderby'], $row['receivedate'], $row['ro_no']
                            ,$row['receiveby'], $row['amt'],$row['total'],$row['statusname'] , $row['status']));
         
        
        
    }else if ($mode_type=='add_shipment'){
        $ar=array();
        $var = getPostArray('list');
        
        $ex_date = explode('/', getPost('date') );
     
        
        $ar["uid"] = getPost('eid');
        $ar["amt"] = getPost('amt');
        $ar["shipment_date"] = $ex_date[2].'/'.$ex_date[1].'/'.$ex_date[0];
        $ar["createdate"] = date("Y/m/d H:i:s");
        $ar['createby'] = $user_id;
        
        $ar['remark'] = getPost( 'remark' );
        $id = $type->InsertShipment($ar);
        
         foreach ($var as $value) {
            $value['sh_id'] = $id;
            if ($type->CheckStock($value['pid'],$value['amt'])){     
                $type->InsertShipmentDetail($value);
                $type->StockUpdate($value['pid'],$value['amt']);
            }
        } 
         
        echo json_encode(array('id' => $id ));
        
    }else if ($mode_type=='add_purchase'){
        $ar=array();
        $var = getPostArray('list');
        $ar['supplier']=getPost('supplier');
        $ar["po_no"] = $type->getRunning("PO");
        $ar["amt"] = getPost('amt'); 
        $ar['discount']=getPost('discount');
        $ar['total']=getPost('total');
		$ar["purchange_date"] = date("Y/m/d");
        $ar["createdate"] = date("Y/m/d H:i:s");
        $ar['createby'] = $user_id;
        $ar['status_po'] = $inital_status_purchase;
        $ar['remark'] = getPost( 'remark' );
        $id = $type->InsertPurchaseData($ar);
        
        foreach ($var as $value) {
            $value['po_id'] = $id;
            $type->InsertPurchaseDataDetail($value);
        }
        $status = $type->getPoStatusById($inital_status_purchase);
        echo json_encode(array('id' => $id, 'status' => $status, 'sid' => $inital_status_purchase));
        
    }else if ($mode_type == 'add_request') {

        $ar = array();
        $var = $_POST['list'];
        $ar["rq_no"] = $_POST['no'];
        $ar["amt"] = $_POST['amt'];
		$ar["request_date"] = date("Y/m/d");
        $ar["createdate"] = date("Y/m/d H:i:s");
        $ar['createby'] = $user_id;
        $ar['status_rq'] = $inital_status;
        $ar['remark'] = getPost('remark');
        $id = $type->InsertData($ar);

        foreach ($var as $value) {
            $value['po_id'] = $id;
            $type->InserDataDetail($value);
        }
        $status = $type->getRequestStatusById($inital_status);

        echo json_encode(array('id' => $id, 'status' => $status, 'sid' => $inital_status));
    }else if ($mode_type=='del_shipment'){
        $id= getPost('id');
       // $type->deleteShipmentDetail($id);
        $type->deleteShipment($id);
    }else if ($mode_type=='checkStock'){
        $pid=getPost('pid');
        $amt=getPost('amt');
        $result = $type->CheckStock($pid,$amt);
        echo json_encode($result);
    }
    else if ($mode_type == 'del') {
        
        $type->deleData($id);
    }/// Age Criteria
	else if ($mode_type='update_pay'){
		$id=$_POST['id'];
		$pay=$_POST['pay_by'];
		$type->update_pay_by($id,$pay);
	}
} else {
    $m_get = filter_input(INPUT_GET,'m');
    if (isset($m_get) && $m_get != "") {
        if ($m_get == 'request'){
            echo json_encode($type->getRequest());
		}else if ($m_get =='year'){
		  echo json_encode($type->getYear_Term());
		}else if ($m_get =='curryear'){
			echo $type->getCurrentYear();
        }else if ($m_get == 'purchase'){
            echo json_encode($type->getPurchase());
        } else if ($m_get =='receive'){
            echo json_encode($type->getReceive());
        }else if ($m_get == 'pdtype'){
            echo json_encode($type->getProductType());
		} else if ($m_get=='supplier'){
			 echo json_encode($type->getSupplier());
		} else if ($m_get=='employee'){
			 echo json_encode($m_emp->getEmployee());
		} else if ($m_get=='curr_emp'){
			 echo json_encode($m_emp->getEmployee());			 
        }else if ($m_get == 'getProduct') {
            $t_product = $_GET['t'];

            $result = $type->loadProduct($t_product);
            $rows = $type->getRowCount();
            $i = 1;
            $html = "";
            if ($rows > 0) {
                $data = array();
                $id = array();

                while ($row = $result->FetchRow()) {
                    $id['id'] = $row['id'];
                    $id['label'] = $row['name'];
                    $data[] = $id;
                }
            } else {
                $data = array();
            }

            ///$arr = array('aaData'=>$data);

            echo json_encode($data);
        }
    }
}
function convertDate($date){
    $ex_date = explode('/',$date);
    return $ex_date[2].'/'.$ex_date[1].'/'.$ex_date[0];
}
function getPost($name){
    
    return filter_input(INPUT_POST,$name,FILTER_DEFAULT);
}
function getPostArray($name){
    
     return filter_input(INPUT_POST,$name,FILTER_DEFAULT,FILTER_REQUIRE_ARRAY);
}
?>